import AJAX from '@/utils/ajax'

class Search {
  constructor() {
    this.searchList = $('.search-list')
    this.timer = null
    this.wdtimer = null
    const that = this
    $('.search-text1')
      .bind('keyup', function(event) {
        const _this = $(this)
        clearTimeout(that.wdtimer)
        that.wdtimer = setTimeout(function() {
          that.show(_this.val(), event)
        }, 300)
      })
      .bind('blur', function() {
        // 鼠标聚焦离开的时候来个延时
        that.timer = setTimeout(function() {
          that.searchList.hide()
        }, 200)
      })
      .bind('focus', function() {
        if (that.searchList.find('ul li').length <= 0) return
        that.searchList.show()
      })
  }
  show(wd) {
    AJAX({ url: 's', data: { wd } }).then(res => {
      if (res.data.length > 0) {
        clearTimeout(this.timer)
        this.searchList.show()
        let h = ''
        this.highLightKeywords(res.data, wd).map(item => {
          h += `<li><a href="${item.url}">${item.name}</a><span>${item.status}</span></li>`
        })
        this.searchList.find('ul').html(h)
      }
    })
  }

  highLightKeywords(data = [], wd) {
    // 正则匹配所有的文本
    if (wd) {
      const re = new RegExp(wd, 'g')
      for (let i = 0; i < data.length; i++) {
        const title = data[i].name || ''
        if (re.test(data[i].name)) {
          data[i].name = title.replace(re, '<em>$&</em>')
        }
      }
    }
    return data
  }
}

export default Search
